package com.sj.uabrowser.mvp.main.view.act;

import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.just.agentweb.AgentWeb;
import com.sj.uabrowser.R;
import com.sj.uabrowser.app.Constant;
import com.sj.uabrowser.app.SPUtil;
import com.sj.uabrowser.app.StatusBarUtil;
import com.sj.uabrowser.db.CollectHistory;
import com.sj.uabrowser.db.gen.CollectHistoryDao;
import com.sj.uabrowser.framework.BaseActivity;
import com.sj.uabrowser.framework.BasePresenter;
import com.sj.uabrowser.mvp.main.bean.MainNewFuncs;
import com.sj.uabrowser.net.AuthResultClient;
import com.sj.uabrowser.net.ServiceApi;

import java.util.Date;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class BrowserAct extends BaseActivity {

    public static final int TYPE_SEARCH = 1;
    public static final int TYPE_FUNC = 2;
    public static final int TYPE_BEAN = 3;
    FrameLayout mViewParent;
    private AgentWeb mAgentWeb;
    View tvClose;
    private CollectHistoryDao collectHistoryDao;
    private CollectHistory bean;

    private int type = TYPE_SEARCH ;

    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_browser;
    }

    @Override
    public void setView() {
        StatusBarUtil.setTransparentForImageView(this,null);
        StatusBarUtil.setColor(this,getResources().getColor(R.color.news_text_selected),0);
        mViewParent = findViewById(R.id.viewParent);
        tvClose = findViewById(R.id.tv_close);
        tvClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        collectHistoryDao = daoSession.getCollectHistoryDao();
        type = getIntent().getIntExtra("type",TYPE_SEARCH);
        String url = "";
        if(type == TYPE_BEAN){
            bean = (CollectHistory) getIntent().getSerializableExtra("bean");
            url = bean.getUrl();
            bean.setDate(new Date().getTime());
            if(!noTrace) {collectHistoryDao.update(bean);}
        }else if(type == TYPE_SEARCH){
            url = getIntent().getStringExtra("url");
            if(!noTrace) {
                List<CollectHistory> histories = collectHistoryDao.queryRaw("where url = ?", new String[]{url});
                if (histories.size() == 0) {
                    bean = new CollectHistory();
                    bean.setUrl(url);
                    bean.setDate(new Date().getTime());
                    bean.setType(CollectHistory.TYPE_NET);
                    bean.setTitle(url);
                    bean.setIsHis(true);
                    collectHistoryDao.insert(bean);
                } else {
                    bean = histories.get(0);
                    bean.setDate(new Date().getTime());
                    collectHistoryDao.update(bean);
                }
            }
        }else if(type == TYPE_FUNC) {
            MainNewFuncs.AdListBean adListBean = (MainNewFuncs.AdListBean) getIntent().getSerializableExtra("adListBean");
            if (adListBean != null) {
                url = adListBean.getUrl();
                String imp = adListBean.getClk_url();
                if(!noTrace) {
                    List<CollectHistory> histories = collectHistoryDao.queryRaw("where url = ?", new String[]{url});
                    if (histories.size() == 0) {
                        bean = new CollectHistory();
                        bean.setUrl(url);
                        bean.setDate(new Date().getTime());
                        bean.setType(CollectHistory.TYPE_NET);
                        bean.setTitle(adListBean.getTitle());
                        bean.setIsHis(true);
                        collectHistoryDao.insert(bean);
                    } else {
                        bean = histories.get(0);
                        bean.setDate(new Date().getTime());
                        collectHistoryDao.update(bean);
                    }
                }
                if (!TextUtils.isEmpty(imp)) {
                    AuthResultClient.getService(ServiceApi.class).rcd(imp).enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {

                        }
                    });
                }

            } else {
                finish();
            }
        }
        loadSearchPage(url);
    }

    @Override
    public void setData() {

    }



    private void loadSearchPage(String url) {
        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(mViewParent, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebViewClient(webViewClient)
                .createAgentWeb()
                .ready()
                .go(url);
        WebView webView = mAgentWeb.getWebCreator().getWebView();
//        WebView初始化之后需要添加如下代码开启Cookie：
        if (android.os.Build.VERSION.SDK_INT >= 21) {
            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
        } else {
            CookieManager.getInstance().setAcceptCookie(true);
        }
        WebSettings webSettings = webView.getSettings();
        int fontSize = SPUtil.get(this,SPUtil.KEY_FONTSIZE, Constant.FONTSIZE_NORMAL);
        webSettings.setDefaultFontSize(fontSize);
        webSettings.setSupportZoom(true);
        //支持javascript
        webSettings.setJavaScriptEnabled(true);
// 设置可以支持缩放
        webSettings.setSupportZoom(true);
// 设置出现缩放工具
        webSettings.setBuiltInZoomControls(true);
//扩大比例的缩放
        webSettings.setUseWideViewPort(true);
//自适应屏幕
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//        webSettings.setLoadWithOverviewMode(true);
//        webView.setDownloadListener(new DownloadListener() {
//            @Override
//            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//                Intent intentUrl = new Intent(BrowserActivity.this, SearchAct.class);
//                intentUrl.putExtra("httpurl", url);
//                startActivity(intentUrl);
//                finish();
//            }
//        });
    }

    private WebViewClient webViewClient = new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            Uri uri = request.getUrl();
            String uriOverride = uri.toString();
            Log.e("uriOverride:", uriOverride);
            if (uriOverride.startsWith("baiduboxlite://")
                    || uriOverride.startsWith("baiduboxapp://")
                    || uriOverride.startsWith("iqiyi://")
                    || uriOverride.startsWith("https://mo.baidu.com/boxandroid")
                    || uriOverride.startsWith("tbopen://")
                    ||uriOverride.startsWith("suning://")

            ) {
                return true;
            }
            return false;
        }


        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            Uri uri = request.getUrl();
            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mAgentWeb != null) {
                mAgentWeb.getIndicatorController().setProgress(100);
            }
            if(type == TYPE_SEARCH&&!noTrace){
                bean.setTitle(view.getTitle());
                daoSession.update(bean);
            }
        }
    };

    @Override
    public void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (mAgentWeb.getWebCreator().getWebView().canGoBack()) {
            mAgentWeb.getWebCreator().getWebView().goBack();
        } else
            super.onBackPressed();
    }

}
